clear all
set more off, perm
local mydir "`1'"
global Tables	`mydir'/XS/Tables
global Work	`mydir'/XS/DataWork
global Raw	`mydir'/XS/DataRaw
global WRDS	`mydir'/WRDS
/* **************************************************************** */
import sas using $WRDS/CRSP/msedelist.sas7bdat, clear
rename *, lower
drop issuno compno hexcd hsiccd
format dlstdt nextdt dlpdt %td
keep if dlstdt>=mdy(6,1,1963)

gen dlstmo=mofd(dlstdt)
format dlstmo %tm
* dlstcd: 1st digit
*1	still trading or halted but not yet delisted
*2	mergers
*3	exchanges
*4	liquidations
*5	delisted by NYSE, NYSE American, NASDAQ, or Arca
*7	delisted by the Securities and Exchange Commission
*8	trading simultaneously on more than one exchange

* nothing to fix if the stock is still trading
drop if  dlstcd==100

gen datem=dlstmo
format datem %tm

keep permco permno datem dlstmo dlstcd dlamt
tempfile fix
save "`fix'", replace
* ***************************
* Need share count to compute total distribution
import sas $WRDS/CRSP/msf.sas7bdat, clear case(lower)
keep if date>=mdy(6,1,1963)

gen datem=mofd(date)
format datem %tm

replace prc=abs(prc)
gen mcap=prc*shrout if prc>0 & shrout>0  

keep permco permno datem shrout prc mcap
* ***************************
merge 1:1 permco permno datem using "`fix'"

tsset permno datem
forvalues x=1(1)6  {
	replace mcap =L`x'.mcap	if _merge==3 & mcap==. 
}
drop if _merge==1

gen distrib=dlamt*shrout
keep permco permno datem shrout prc mcap dlstmo dlstcd dlamt distrib  

save "`fix'", replace
count 
* ***************************
import sas using $WRDS/CRSP/stocknames.sas7bdat, clear case(lower)
rename *, lower

keep permco permno namedt nameenddt shrcd exchcd
duplicates drop

* find end-of-the-month day for the last record of each stock
sort permco permno nameenddt
bys permco permno:  gen obs=_n
bys permco permno:  gen tot=_N
replace nameenddt=mdy(12,31,year(nameenddt)) 			if month(nameenddt)==12 & obs==tot
replace nameenddt=mdy(month(nameenddt)+1,1,year(nameenddt))-1	if month(nameenddt)<=11 & obs==tot
drop obs tot

joinby permco permno using "`fix'"
keep if (shrcd==10 | shrcd==11) 
keep if (exchcd>=1 & exchcd<=3)

sort permco datem mcap
collapse (sum) distrib (lastnm) permno dlstcd dlstmo, by(permco datem)
sort permco

order permco permno datem dlstmo dlstcd distrib
* ***************************
save $Work/Delistings02, replace
